﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Windows.Forms;

namespace docExplorer
{
    public static class XMLUtils
    {
        #region Properties
        private static string xmlPath = AppDomain.CurrentDomain.BaseDirectory + "appData\\explorer.xml";
        public static string XmlPath
        {
            get { return XMLUtils.xmlPath; }
        }

        private static XElement xExplorer = XElement.Load(xmlPath);
        public static XElement XExplorer
        {
            get { return XElement.Load(xmlPath); }
        }
        #endregion

        public static XElement RenameElement(XElement e, string newName, XNamespace ns)
        {
            XElement newElement = new XElement(ns + newName);
            if (e.HasAttributes)
            {
                IEnumerable<XAttribute> atributos = e.Attributes();
                foreach (var atributo in atributos)
                {
                    newElement.Add(new XAttribute(atributo));
                }
            }
            newElement.Add(e.Elements());
            e.ReplaceWith(newElement);
            return newElement;
        }

        public static void ConstructXML(TreeNode nodeRoot)
        {
            XDocument xNewExplorer = new XDocument(new XElement("docExplorer", new XAttribute("type", "Root")));
            foreach (TreeNode childNode in nodeRoot.Nodes)
            {
                xNewExplorer.Root.Add(xElementToSave(childNode));
            }
            xNewExplorer.Save(xmlPath);
        }

        private static XElement xElementToSave(TreeNode node)
        {
            XElement xElement = new XElement(node.Text.Replace(" ",""),
                                    new XAttribute("type", ((TreeNodeContents)node.Tag).Type.ToString()),
                                    new XAttribute("path", ((TreeNodeContents)node.Tag).Path),
                                    new XAttribute("template", ((TreeNodeContents)node.Tag).Template),
                                    new XAttribute("create", ((TreeNodeContents)node.Tag).Create));
            
            foreach (TreeNode childNode in node.Nodes)
            {
                xElement.Add(xElementToSave(childNode));
            }

            return xElement;
        }

        /*public static TreeNodeContents[] RetrieveCategorysByParent(XElement parent)
        { 
                
        }*/
    }
}
